<?php

$app->get('/categories/:id', function ($id) use ($app, $c, $redis) {
    if (!$id) {
        $app->notFound();
        return;
    }
    $size = 20;
    $nodes = array();
    $categoriesKey = 'haha-blue-categories-by-slug-' . $id;
    $ids = array();

    $data = $redis->get($categoriesKey);
    if (!$data) {
        $termTable = $c['Blue\Table\Term'];
        $termTaxonomyTable = $c['Blue\Table\TermTaxonomy'];

        $sql = new \Zend\Db\Sql\Sql($termTable->getAdapter());
        $select = $sql->select()
            ->from(array('a' => $termTable->getTable()))
            ->join(array('b' => $termTaxonomyTable->getTable()),
                'a.id=b.term_id',
                array('taxonomyId' => 'id', 'parent' => 'parent_id'))
            ->where(array('b.taxonomy' => 'category', 'a.slug' => $id));

        $term = null;
        foreach ($sql->prepareStatementForSqlObject($select)->execute() as $item) {
            $term = (object)$item;
            break;
        }
        if (!$term) {
            $app->notFound();
            return;
        }
        $ids[] = $term->taxonomyId;
        if (!$term->parent) {
            $select->reset(\Zend\Db\Sql\Select::WHERE)
                ->where(array('b.taxonomy' => 'category', 'b.parent_id' => $term->id));
            foreach ($sql->prepareStatementForSqlObject($select)->execute() as $item) {
                $ids[] = $item['taxonomyId'];
            }
        }
        $redis->set($categoriesKey, json_encode($ids));
        $redis->expire($categoriesKey, 600);
    } else {
        $ids = json_decode($data);
    }

    $random = $app->request->get('random', false);
    if ($random) {
        $nodeTable = $c['Blue\Table\Node'];
        $nodeTaxonomyTable = $c['Blue\Table\NodeTaxonomy'];

        $key = 'haha-blue-categories-' . $id . '-random-nodes';
        if (!$redis->exists($key)) {
            $sql = new \Zend\Db\Sql\Sql($nodeTable->getAdapter());
            $select = $sql->select()
                ->from(array('a' => $nodeTable->getTable()))
                ->columns(array('id'))
                ->join(array('b' => $nodeTaxonomyTable->getTable()),
                    'a.id=b.node_id',
                    array())
                ->where(array('b.term_taxonomy_id' => $ids));

            foreach ($sql->prepareStatementForSqlObject($select)->execute() as $item) {
                $redis->sadd($key, $item["id"]);
            }
            $redis->expire($key, 300);
        }

        foreach ($nodeTable->select(function (Zend\Db\Sql\Select $select) use ($redis, $key, $size) {
            $select->columns(array('id', 'title', 'created_at'))->where(array('id' => $redis->srandmember($key, $size)));
        }) as $item) {
            //$item = (object)$item;
            $item->created_at = date('Y-m-d', strtotime($item->created_at));
            $nodes[] = $item;
        }
    } else {
        $page = $app->request->get('page', 1);


        $key = 'haha-blue-category-' . $id . '-nodes-p' . $page;

        $data = $redis->get($key);

        if (!$data) {
            $nodeTable = $c['Blue\Table\Node'];
            $nodeTaxonomyTable = $c['Blue\Table\NodeTaxonomy'];

            $sql = new \Zend\Db\Sql\Sql($nodeTable->getAdapter());
            $select = $sql->select()
                ->from(array('a' => $nodeTable->getTable()))
                ->columns(array('id', 'title', 'created_at'))
                ->join(array('b' => $nodeTaxonomyTable->getTable()),
                    'a.id=b.node_id',
                    array())
                ->where(array('b.term_taxonomy_id' => $ids))
                ->order('a.id desc')
                ->offset(($page - 1) * $size)
                ->limit($size);

            foreach ($sql->prepareStatementForSqlObject($select)->execute() as $item) {
                $item = (object)$item;
                $item->created_at = date('Y-m-d', strtotime($item->created_at));
                $nodes[] = $item;
            }

            $redis->set($key, json_encode($nodes));
            $redis->expire($key, 300);
        } else {
            $nodes = json_decode($data);
        }
    }

    $app->contentType('application/json; charset=utf8');
    echo json_encode(array_values($nodes));
})->name('blue-category');
$app->get('/categories', function () use ($app, $c, $redis) {
    $model = array();
    $key = 'haha-blue-all-categories';
    $data = $redis->get($key);
    if (!$data) {
        $termTable = $c['Blue\Table\Term'];
        $termTaxonomy = $c['Blue\Table\TermTaxonomy'];

        $sql = new \Zend\Db\Sql\Sql($termTable->getAdapter());
        $select = $sql->select()
            ->from(array('a' => $termTable->getTable()))
            ->join(array('b' => $termTaxonomy->getTable()),
                'a.id=b.term_id',
                array('taxonomyId' => 'id', 'parent' => 'parent_id'))
            ->where(array('b.taxonomy' => 'category'))->order('b.parent_id asc,a.id asc');

        foreach ($sql->prepareStatementForSqlObject($select)->execute() as $item) {
            $item = (object)$item;
            if ($item->parent) {
                $model[$item->parent]->children[] = $item;
            } else {
                $item->children = array();
                $model[$item->id] = $item;
            }
        }
        $model = array_values($model);
        $redis->set($key, json_encode($model));
        $redis->expire($key, 30 * 60);
    } else {
        $model = json_decode($data);
    }
    $app->expires('+1 day');
    $app->contentType('application/json; charset=utf8');
    echo json_encode($model);
})->name('blue-categories');
